<template>
  <div class="address-lists-container">
    <div class="address-header-container">
      <div class="address-header"
          v-if="addressInfo.showBackButton">
        <a
          @click="handleClickBackBtn"
          href="javascript:;"
          class="btn-back">
          <!-- TODO 返回按钮替换 -->
          <span class="icon-back"></span>
        </a>
        <span>{{addressInfo.headerTitle}}</span>
      </div>
      <!-- 搜索 -->
      <search :searchInfo="searchInfo"
              @search="searchAddress"></search>
    </div>

    <div v-if="addLists.length!=0">
      <div class="address-lists">
        <div class="address-tips" v-if="orderEdit"><img src="https://img.wifenxiao.com/h5-wfx/images/icon_tips.png">商品可能已交付快递公司，修改地址需要商家审核</div>
        <van-list v-model="loading"
                  :finished="finished"
                  finished-text=""
                  @load="onLoad"
                  :offset="offset"
                  :immediate-check="immediateCheck">
          <div class="address-item"
               v-for="(item,index) in addLists"
               :key="item.address_id">
            <div
              @click="selectAddress(item)"
              class="address-info">
              <p class="name-mobile clearfix">
                <span class="name fl">{{item.name}}</span>
                <span class="mobile fr">{{item.mobile}}</span>
              </p>
              <p class="addr-detail">{{item.province}}{{item.city}}{{item.area}}{{item.town}}{{item.address}}</p>
            </div>
            <div class="actions-new clearfix">
              <div href="javascript:;"
                   class="btn-check fl j-addrM-setDefault"
                   :class="item.is_default_address==1?'checked':''"
                   @click="clickDefault(index,item)">
                <i class="icon-check bdbox"></i>
                <span>默认地址</span>
              </div>

              <div class="btn clearfix">
                <a href="javascript:;"
                   class="fr addrM j-addrM-del del-btn"
                   @click.stop="clickDelAddress(item)">
                  <span>删除</span>
                </a>
                <a href="javascript:;"
                   class="fr addrM j-addrM-edit edit-btn"
                   @click.stop="clickEditAddress(item)">
                  <span>编辑</span>
                </a>
                <span class="fr now_address" v-if="orderEdit && now_address_id==item.address_id">当前收货地址</span>
              </div>
            </div>
          </div>
        </van-list>
      </div>

    </div>
    <div v-else>
      <div class="address-tips" v-if="orderEdit">商品可能已交付快递公司，修改地址需要商家审核</div>
      <div class="no-address">
        <img :src="noAddress"
             alt="">
        <p>你还没有收货地址哟～</p>
      </div>
    </div>
    <div class="address-add-btn">
      <div class="clearfix twobtn"
           v-if="isWxBtn && showSyncWechatAddressBtn == 1">
        <a href="javascript:;"
           class="fr red-gra-btn j-addrM-add add-btn"
           @click="clickAddAddress"><i></i>添加新地址</a>
        <a href="javascript:;"
           @click="addrMSyncWechat"
           class="fl green j-addrM-syncWechat wechat-btn">同步微信地址</a>
      </div>
      <div class="bottom red-gra-btn"
           v-else
           @click="clickAddAddress">
        <i></i>添加新地址
      </div>
    </div>
    <edit-address :editInfo="editInfo"
                  :dingguagua_dz_is_freight="dingguagua_dz_is_freight"
                  @init="init"></edit-address>
    <!-- 确定修改地址 -->
    <van-dialog
      v-model="showConfirmAddress"
      show-cancel-button
      confirm-button-text="确定"
      cancelButtonText="我再看看"
      class="common-confirm"
      @confirm="confirmAddress"
    >
    <div class="donation-box">
        <div class="con-box">
          <div class="title">请确定修改后收货信息</div>
          <div class="input-box">
            <div class="tongMsg">{{selectAddressInfo.name}} {{selectAddressInfo.mobile}}</div>
            <div class="tongMsg">{{selectAddressInfo.province}}{{selectAddressInfo.city}}{{selectAddressInfo.town}}{{selectAddressInfo.address}}</div>
          </div>
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import Vue from 'vue'
import QQMapWX from '@/smallapp/qqmap-wx-jssdk.js'
import { isWeixinCient } from '@/utils/validate'
import { List, Dialog } from 'vant'
import small from '@/smallapp/small'

Vue.use(List)
Vue.use(Dialog)
import EditAddress from '@/components/EditAddress/index'
import Search from '@/components/Search/index'
import {
  getAddressList,
  setDefaultAddress,
  delAddress,
  sysncrWxAddress
} from '@/api/user/address.js'

export default Vue.extend({
  name: 'index',
  components: {
    EditAddress,
    Search
  },
  props: {
    addressInfo: {
      type: Object,
      default: {
        showBackButton: 1,
        headerTitle: '收货地址',
        searchInfoText: ''
      }
    },
    changeTitle: {
      type: Boolean,
      default: true
    },
    dingguagua_dz_is_freight: {
      type: [String, Number],
      default: 0
    },
    orderEdit: {
      type: Boolean,
      default: false
    },
    now_address_id: {
      type: [String, Number],
      default: 0
    }
  },
  data() {
    return {
      searchInfo: {
        placeholder: '请输入姓名或者手机号'
      },
      noAddress: 'https://img.wifenxiao.com/h5-wfx/images/user/no-address.png',
      showSyncWechatAddressBtn: '0',
      isWxBtn: false,
      loading: false,
      finished: false,
      offset: 20,
      immediateCheck: false,
      p: 1,
      editInfo: {
        isNeedAddress: 1,
        isNeedTown: 1,
        isNeedTownMust: 1,
        type: 'add',
        show: false,
        areaBtnTextEdit: '',
        areaBtnTextEditTown: '',
        TextareaDel: false,
        addrDetail: {},
        isNeedLatLng: '0' // 是否开通蜂鸟配送，需要获取地址的经纬度
      },
      addLists: [],
      showConfirmAddress: false,
      selectAddressInfo: {}
    }
  },
  methods: {
    // 同步微信地址存到会员地址中
    handleSysncrWxAddress(res) {
      const data = {
        name: res.userName,
        mobile: res.telNumber,
        province: res.provinceName,
        city: res.cityName,
        area: res.countyName,
        address: res.detailInfo,
        zip: res.postalCode,
        latitude: res.latitude,
        longitude: res.longitude
      }
      sysncrWxAddress(data).then((res) => {
        if (res.status == 1) {
          this.init(1)
          this.$Error('同步微信地址成功')
        } else {
          this.$Error(res.msg || '获取地址失败')
        }
      })
    },

    // 处理
    openAddressSta(res) {
      const msg = 'chooseAddress:ok'
      const that = this
      if (res.errMsg == msg) {
        // 开启了蜂鸟配送需要经纬度
        if (this.editInfo.isNeedLatLng == 1) {
          const address = (res.provinceName + res.cityName + res.countyName + res.detailInfo).replace(/\s+/g, '')
          const qqmapsdk = new QQMapWX({
            key: small.wxCache('tencentMapKey') // 必填
          })
          qqmapsdk.geocoder({
            // 获取表单传入地址
            address, // 地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
            success(response) { // 成功后的回调},
              res.latitude = response.result.location.lat
              res.longitude = response.result.location.lng
              that.handleSysncrWxAddress(res)
            },
            fail(error) {
              that.$Error('获取经纬度失败，请稍后再试')
              // console.error(error);
            }
          })
        } else {
          that.handleSysncrWxAddress(res)
        }
      } else {
        this.$Error('获取地址失败!')
      }
    },
    searchAddress(key) {
      this.addressInfo.searchInfoText = key
    },
    // 点击返货按钮
    handleClickBackBtn() {
      this.$emit('backEvent')
    },
    init(onload) {
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 10000)
      if (onload == 1) {
        this.p = 1
        this.addLists = []
      }
      const data = {
        p: this.p,
        key: this.addressInfo.searchInfoText
      }
      getAddressList(data).then((res) => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          const resData = res.data
          if (this.changeTitle) {
            wx.setNavigationBarTitle({
              title: resData.ftitle_address
            })
          }
          this.editInfo.isNeedAddress = resData.is_select_psq
          this.editInfo.isNeedTown = resData.is_select_town
          this.editInfo.isNeedLatLng = resData.is_store_fn_pt // 是否开通蜂鸟配送，需要获取地址的经纬度
          this.showSyncWechatAddressBtn = resData.is_get_wxaddress
          if (resData.addressList && resData.addressList.length) {
            var length = resData.addressList.length
          } else {
            this.finished = true
            return
          }
          if (length < 20) this.finished = true
          this.addLists = this.addLists.concat(resData.addressList)
          this.p += 1
        } else {
          this.$Error(res.msg)
        }
      })
    },
    // 点击同步微信地址
    addrMSyncWechat() {
      const that = this
      wx.getSetting({
        success(res) {
          // console.log("vres.authSetting['scope.address']：", res.authSetting['scope.address'])
          if (res.authSetting['scope.address']) {
            wx.chooseAddress({
              success(res) {
                that.openAddressSta(res)
              }
            })
          } else if (res.authSetting['scope.address'] == false) {
            wx.openSetting({
              success(res) {
                // console.log(res, 456)
              }
            })
          } else {
            // console.log('eee')
            wx.chooseAddress({
              success(res) {
                that.openAddressSta(res)
              }
            })
          }
        }
      })
    },
    // 点击添加新地址
    clickAddAddress() {
      this.editInfo.addrDetail = {
        address_id: '',
        name: '',
        mobile: '',
        province: '',
        city: '',
        area: '',
        town: '',
        zip: '', // 邮政编码
        address: '',
        type: 'add'
      }
      this.editInfo.areaBtnTextEdit = ''
      this.editInfo.show = true
      this.editInfo.TextareaDel = true
    },
    // 设为默认地址
    clickDefault(index, item) {
      const data = {
        id: item.address_id
      }
      const addLists = this.addLists
      addLists.forEach((element, num) => {
        this.$set(this.addLists[num], 'is_default_address', '0')
      })
      this.addLists[index].is_default_address == '1'
      this.$set(this.addLists[index], 'is_default_address', '1')
      this.$loadingWrap.show()
      setTimeout(() => {
        this.$loadingWrap.close()
      }, 10000)

      setDefaultAddress(data).then((res) => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          this.$Error('设置成功')
        } else {
          this.$Error(res.msg)
        }
      })
    },
    // 编辑地址
    clickEditAddress(item) {
      this.editInfo.show = true
      this.editInfo.TextareaDel = true
      this.editInfo.type = 'edit'
      this.editInfo.areaBtnTextEditTown = item.town
      this.editInfo.addrDetail = {
        address_id: item.address_id,
        name: item.name,
        mobile: item.mobile,
        province: item.province_id,
        city: item.city_id,
        area: item.area_id,
        town: item.town_id,
        zip: item.zip, // 邮政编码
        address: item.address,
        latitude: item.latitude,
        longitude: item.longitude
      }
      this.editInfo.firstIn = true
      this.editInfo.areaBtnTextEdit =
        `${item.province}\xa0\xa0${item.city}\xa0\xa0${item.area}`
    },
    // 删除地址
    clickDelAddress(item) {
      Dialog.confirm({
        message: '确定删除吗？',
        confirmButtonText: '确定',
        className: 'common-confirm',
        closeOnClickOverlay: true
      }).then(() => {
        const data = {
          address_id: item.address_id
        }
        delAddress(data).then((res) => {
          if (res.status == 1) {
            this.init(1)
            this.$Error('删除地址成功')
          } else {
            this.$Error(res.msg)
          }
        })
      })
    },
    onLoad() {
      setTimeout(() => {
        this.init()
        this.loading = false
      }, 500)
    },
    // 选择地址
    selectAddress(item) {
      if (this.orderEdit) {
        this.showConfirmAddress = true
        this.selectAddressInfo = item
        return
      }
      this.$emit('selectAddress', item)
    },
    confirmAddress() {
      this.$emit('selectAddress', this.selectAddressInfo)
    }
  },
  watch: {
    // 监听县区的变化
    'addressInfo.searchInfoText': {
      handler(val) {
        // console.log(val)
        this.init(1)
      },
      deep: true
    }
  },
  created() {
    // 判断微信环境 决定同步微信地址按钮
    if (isWeixinCient()) {
      this.isWxBtn = true
    } else {
      this.isWxBtn = false
    }
    this.init()
  }
})
</script>

<style lang="scss">
.address-lists-container {
  border-top: 2px solid #f5f5f5;
  padding: 20px 25px;
  .icon-back{
    border: solid #666;
    border-width: 0 3px 3px 0;
    display: inline-block;
    padding: 8px;
    transform: rotate(135deg);
    -webkit-transform: rotate(135deg);
  }
  .address-header-container{
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 11;
    border-radius: 0 0 20px 20px;
    overflow: hidden;
  }
  .address-lists{
    padding: 108px 0 108px;
  }
  .address-header {
    width: 100%;
    height: 100px;
    line-height: 94px;
    background: #fff;
    border-bottom: 2px solid #f5f5f5;
    text-align: center;
    .btn-back {
      position: absolute;
      left: 0;
      top: 0;
      display: block;
      width: 80px;
      height: 94px;
      padding-top: 4px;
    }
    .icon-backg {
      font-size: 40px;
    }
    span {
      font-size: 32px;
    }
  }
  .address-item {
    margin-bottom: 20px;
    padding: 30px;
    background: #fff;
    border-radius: 20px;
    .address-info {
      border-bottom: 1px solid #f5f5f5;
      .name-mobile {
        font-size: 32px;
        line-height: 50px;
        color: #333;
        .name{
          font-weight:bold;
        }
      }
      .addr-detail {
        font-size: 26px;
        line-height: 1.4;
        color: #999999;
        padding: 20px 0 30px;
      }
    }
    .actions-new {
      padding-top: 26px;
      color: #999;
      font-size: 28px;
      line-height: 36px;
      .btn-check {
        .icon-check {
          float: left;
          width: 36px;
          height: 36px;
          margin-right: 8px;
          border: 3px solid #cecece;
          border-radius: 50%;
          vertical-align: middle;
        }
        &.checked {
          .icon-check {
            border: 0;
            background: url("https://img.wifenxiao.com/h5-wfx/images/selected.png") no-repeat;
            background-size: 100% 100%;
          }
          span {
            color: #f20b22;
          }
        }
      }
      .btn {
        a {
          display: block;
          padding: 0 30px;
        }
        .del-btn {
          padding-right: 0;
          position: relative;
          &::before {
            content: "";
            position: absolute;
            width: 2px;
            height: 26px;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            background: #999999;
          }
        }
      }
    }
  }
  .address-add-btn {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    font-size: 32px;
    text-align: center;
    color: #fff;
    background: #fff;
    padding: 11px 25px;
    box-sizing: border-box;
    .bottom {
      height: 76px;
      line-height: 76px;
      border-radius: 76px;
      // box-shadow: 0 5px 13px rgba(199, 67, 0, 0.5);
      i {
        display: inline-block;
        width: 28px;
        height: 28px;
        margin-right: 8px;
        background: url("https://img.wifenxiao.com/h5-wfx/images/icon_add.png") no-repeat;
        background-size: 100% 100%;
        vertical-align: -2px;
      }
    }
    .twobtn {
      margin: 0 20px;
      height: 80px;
      line-height: 80px;
      font-size: 28px;
      font-weight: bold;
      a {
        width: 50%;
        &.add-btn {
          border-radius: 0 80px 80px 0;
          i {
            display: inline-block;
            width: 28px;
            height: 28px;
            margin-right: 8px;
            background: url("https://img.wifenxiao.com/h5-wfx/images/icon_add.png") no-repeat;
            background-size: 100% 100%;
            vertical-align: -2px;
          }
        }
        &.wechat-btn {
          background: linear-gradient(to right, #FFAE00, #FF8A02);
          border-radius: 80px 0 0 80px;
        }
      }
    }
  }
  .no-address {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    img {
      display: block;
      width: 178px;
      height: 186px;
      margin: 0 auto;
    }
    p {
      font-size: 28px;
      color: #666666;
      margin-top: 35px;
    }
    .no-address-btn {
      width: 226px;
      line-height: 72px;
      border: 2px solid #f20b22;
      border-radius: 38px;
      text-align: center;
      font-size: 28px;
      color: #f20b22;
      margin: 64px auto 0;
      .icon_add {
        color: #f20b22;
      }
    }
  }
}
.address-tips {
  padding: 10px 20px;
  background: #FFECE8;
  color: #f20b22;
  font-weight: 500;
  margin-bottom: 20px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  font-size: 24px;
  line-height: 40px;
  img {
    width: 30px;
    height: 30px;
    margin-right: 10px;
  }
}
.now_address {
  font-size: 22px;
  position: relative;
  right: 40px;
  color: #f20b22!important
}
.donation-box{
  .con-box{
    position:relative;
    padding:40px 60px;
  }
  .title {
    font-size: 35px;
    color: #333;
    font-weight: 600;
    text-align: center;
    margin-bottom: 40px;
  }
  .input-box{
    margin:16px 0;
    font-size:28px;
    .tongMsg {
      margin-top: 10px;
    }
  }
}
</style>
